<?php
namespace App\Http\Controllers;
use App\Model\GoodsModel;
use App\Service\GoodsService;
use Illuminate\Http\Request;
use App\People;
use App\Order;
use App\Goods;
use App\OrderGoods;
use App\Service\PeopleService;
use App\Cart;
use zgldh\QiniuStorage\QiniuStorage;

class TestController extends  Controller
{
    private $goodsService;
    private $peopleService;
    private $goods;
    public function __construct(GoodsService $goodsService,Request $request,PeopleService $peopleService)
    {
        $goods_id=$request->goods_id;
        $this->goods=Goods::where("id",$goods_id)->first();
        $this->goodsService=$goodsService;
        $this->peopleService=$peopleService;
    }
    /**
     * 七牛云上传
     *
     */
    public function upload(Request $request)
    {
        if($request->file('file'))
        {
           $file=$request->file('file');
//            return $file;
            $disk=QiniuStorage::disk('qiniu');
            $fileName=md5($file->getClientOriginalName().time().rand()).'.'.$file->getClientOriginalExtension();
            $bool=$disk->put("iwanli/image_".$fileName,file_get_contents($file->getRealPath()));
            if($bool)
            {
                $path=$disk->downloadUrl('iwanli/image_'.$fileName);
                return $path;
            }
        }
    }
    /**
     * @return int
     * 详情页
     */
    public function test($id)
    {
//        return 1;
        $success=GoodsModel::find($id);
        return ["code"=>200,"message"=>"详情页查看成功","data"=>$success];
    }
    /**
     * 生成订单接口
     */
    public function create(Request $request)
    {
        $token=$request->token;
//        return $token;
        $user=People::where("token",$token)->first();
        if(empty($user))
        {
            return ['code'=>200,'msg'=>'token错误','data'=>$user];
        }
        $goods=Goods::find($request->goods_id);
        //将订单编号 订单总金额 用户id入库
        $data['order_number']=$this->getOrderNo();
        $data['order_price']=$goods->sell_price * $request->buy_num;
        $data['user_id']=$user->id;
        $order=Order::create($data);
        //订单表入库的同时
        //将商品id 用户id 订单id 总金额 购买数量入库到订单商品表
        $result=OrderGoods::create([
            'goods_id'=>$request->goods_id,
            'user_id'=>$user->id,
            'order_id'=>$order->id,
            'total_price'=>$order->order_price,
            'buy_num'=>$request->buy_num,
        ]);
        //减少库存
        $goods->store_nums=$goods->store_nums - $request->buy_num;
        $goods->save();
        if($result)
        {
            return ['code'=>200,'msg'=>'订单已经生成','data'=>$result];
        }
        else{
            return ['code'=>400,'msg'=>'订单生成失败','data'=>$result];
        }

    }

    /**
     * @return $request
     * 生成订单编号
     */
    public function  getOrderNo()
    {
        return date('YmdHis',time()).rand(1000,9999);
    }
    /**
     * 商品列表（分页）
     */
//    public function showss(Request $request)
//    {
//        $page=$request->input('page');
//        $pageSize=2;
//        $offset=($page-1)*$pageSize;
//        $data['goods']=$this->goodsService->showPage($offset,$pageSize);
//        $data['count']=$this->goodsService->showCount();
//        $data['page_size']=$pageSize;
//    }
    /**
     * 商品列表并分页(第一次从数据库读取，第二次从redis读取)
     */
    public function goodsList(Request $request)
    {
//        return 1;
        $redis=new \Redis();
        $redis->pconnect('127.0.0.1',6379);
//        $redis->flushAll();
        $page=$request->input('page');
        $pageSize=2;
        $offset=($page-1)*$pageSize;
        $data['goods']=$this->goodsService->showPage($offset,$pageSize);
        $data['count']=$this->goodsService->showCount();
        $data['page_size']=$pageSize;
        $key=json_encode($data);
//        var_dump($key);die;
        $res = $redis->get($key);
        if(empty($res))
        {
            $redis->set($key,json_encode($data));
            return ["code"=>200,"message"=>"数据库读取成功","data"=>$data];
        }
        else{
            return ["code"=>200,"message"=>"redis读取成功","data"=>$data];
        }
    }
    /**
     * 订单表
     */
    public function orderList()
    {
//        return 1;
        $success=Order::all();
        return ["code"=>200,"message"=>"订单查看成功","data"=>$success];
    }
    //商品redis收藏
    public function collect(Request $request)
    {
        $token=$request->token;
//        return $token;
        $user= People::where("token",$token)->first();
//        return $user;
        $user_id=$user->id;
        $redis=new \Redis();
        $redis->pconnect('127.0.0.1',6379);
//        $redis->flushAll();die;
        $key="collect:".$user_id;
        $data=$redis->get($key);
        $data['goods_id']=$this->goods->id;
        $data['user_id']=$user->id;
        if(empty($data))
        {
           $redis->sadd($key,json_encode($data));
            return ["code"=>200,"message"=>"收藏成功","data"=>$data];
        }
        else{
           $arr=$redis->sIsMember($key,json_encode($data));
//            var_dump($arr);die;
            if($arr)
            {
                return ["code"=>400,"message"=>"亲，你已经收藏过了,请选择其他商品","data"=>null];
            }
            else{
                $redis->sadd($key,json_encode($data));
                return ["code"=>200,"message"=>"收藏成功","data"=>$data];
            }

        }
    }
    //商品redis取消收藏
    public function nocollect(Request $request)
    {
        $token=$request->token;
        $user= People::where("token",$token)->first();
        $user_id=$user->id;
        $redis=new \Redis();
        $redis->pconnect('127.0.0.1',6379);
//        $redis->flushAll();die;
        $key="collect:".$user_id;
        $arr=$redis->del($key);
        if($arr)
        {
            return ["code"=>200,"message"=>"取消收藏成功","data"=>null];
        }
        return ["code"=>200,"message"=>"取消收藏失败","data"=>null];
    }
    //加入购物车接口(入库)
    public function addCart(Request $request)
    {
        $token=$request->token;
        $user= People::where("token",$token)->first();
        $data=Cart::where([
             ["user_id",'=',$user->id],//用户id
            ["goods_id",'=',intval($request->goods_id)],
       ])->first();
        if(empty($data))
        {
            //直接添加
            $goods=Goods::find(intval($request->goods_id));//获取这个商品的所有信息
//            return $goods;
            $cartData['goods_id']=intval($request->goods_id);
            $cartData['user_id']=$user->id;
            $cartData['buy_num']=intval($request->buy_num);
            $cartData['goods_price']=$goods->sell_price;
            $cartData['goods_name']=$goods->name;
            if(Cart::create($cartData))
            {
                return ["code"=>200,"message"=>"购物车添加成功","data"=>$cartData];
            }
        }
        else
        {
            $data->buy_num=$data->buy_num+intval($request->buy_num);
            $data->save();
            $user=People::where("token",$token)->first();
            $key="cart:".$user->id;
            $redis=new \Redis();
            $redis->pconnect('127.0.0.1',6379);
            $exit=$redis->hExists($key,intval($request->goods_id));
            if(empty($exit))
            {
                $arr=$redis->hSet($key,$request->goods_id,$request->buy_num);
                if($arr)
                {
                    return ["code"=>200,"message"=>"redis购物车成功","data"=>$arr];
                }
                else{
                    return ["code"=>400,"message"=>"redis购物车失败","data"=>null];
                }
            }
            else
            {
                $arr=$redis->hIncrBy($key,$request->goods_id,$request->buy_num);
                if($arr)
                {
                    return ["code"=>200,"message"=>"redis购物车成功","data"=>$arr];
                }
                else{
                    return ["code"=>400,"message"=>"redis购物车失败","data"=>null];
                }
            }

        }
    }
    //点赞功能(redis)
    public function dz(Request $request)
    {
        $token=$request->token;
//        $goods_id=$request->id;
//        $data=Goods::where(["id",'=',$goods_id])->first();
//        if($data)
//        {
//            $cartData[0]['dz_many']=$request->dz_many+1;
//            $data=Goods::create($cartData);
//            $data->save();
//        }
        $user=People::where("token",$token)->first();
        $key="dz:".$user->id;
        $redis=new \Redis();
        $redis->pconnect('127.0.0.1',6379);
//        $redis->flushAll();die;
        $exit=$redis->hExists($key,intval($request->goods_id));
        if(empty($exit))
        {
            $arr=$redis->hSet($key,$request->goods_id,$request->dz_many);
            if($arr)
            {
                return ["code"=>200,"message"=>"redis点赞成功","data"=>$arr];
            }
            else{
                return ["code"=>400,"message"=>"redis点赞失败","data"=>null];
            }
        }
        else
        {
            $arr=$redis->hIncrBy($key,$request->goods_id,$request->dz_many);
            if($arr)
            {
                return ["code"=>200,"message"=>"redis点赞成功","data"=>$arr];
            }
            else
            {
                return ["code"=>400,"message"=>"redis点赞成功","data"=>null];
            }

        }
    }
    //redis取消点赞
    public function nodz(Request $request)
    {
        $token=$request->token;
        $user= People::where("token",$token)->first();
        $redis=new \Redis();
        $redis->pconnect('127.0.0.1',6379);
        $key="dz:".$user->id;
        $arr=$redis->del($key);
        if($arr)
        {
            return ["code"=>200,"message"=>"取消点赞成功","data"=>null];
        }
        return ["code"=>200,"message"=>"取消取消失败","data"=>null];
    }
    //redis排行榜(有序集合做)
    public function rank()
    {

    }
}